package com.ysm.smfu.activity;

import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.adapter.BaseListAdapter;
import com.ysm.smfu.adapter.TypeAdapter;
import com.ysm.smfu.bean.HomeSearchResultBean;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.RefreshLayout;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/9/23.
 */
public class SearchActivity extends BaseRefreshActivity<HomeSearchResultBean.BusinessInfo> {

    @BindView(R.id.act_search_listView)
    ListView actSearchListView;
    @BindView(R.id.refresh)
    RefreshLayout refresh;


    @BindView(R.id.activity_search)
    EditText activitySearch;
    @BindView(R.id.query)
    TextView query;

    //    GridView searchOld;
//    TextView hisSearch;
    AutoLinearLayout listInfo;
    @BindView(R.id.only_no)
    ImageView only_no;
    private String lat;
    private String lon;
    private BaseListAdapter adapter;
    private String cityId;
    private String currCityId;
    private SharedPreferences currShared;
    private String keyWord;
    private MyAdapter adapter1;
    private String[] historyStrings;
    private AlertDialog dialog;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initHeadView();
        initRefresh(refresh, true);
        getConfig();
        query.setOnClickListener(this);
    }

    /**
     * 初始化头布局
     */
    private void initHeadView() {
        View headView = UIUtils.inflate(R.layout.head_search);
        actSearchListView.addHeaderView(headView);
//        searchOld = (GridView) headView.findViewById(R.id.search_old);
//        hisSearch = (TextView) headView.findViewById(R.id.hisSearch);
        listInfo = (AutoLinearLayout) headView.findViewById(R.id.listInfo);
    }

    /**
     * 获取配置信息
     */
    private void getConfig() {
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        String name = sp.getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        cityId = sp.getString(SpKey.SELECID, "");
        currCityId = sp.getString(SpKey.LOCID, "");
        lat = sp.getString(SpKey.LAT, "");
        lon = sp.getString(SpKey.LON, "");
    }

    @Override
    protected void initData() {
        super.initData();
        //      搜索后刷新
        adapter = new BaseListAdapter(datas, actSearchListView, this);
        actSearchListView.setAdapter(adapter);
//        adapter1 = new MyAdapter(historyStrings);
//        searchOld.setAdapter(adapter1);
//        searchOld.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String historyString = historyStrings[position];
//                activitySearch.setText(historyString);
//                search(historyString);
//            }
//        });
//        dealSearchOld();
    }

    StringBuffer sb = new StringBuffer();

    @Override
    public void onInnerClick(View v) {
        super.onInnerClick(v);
        keyWord = activitySearch.getText().toString().trim();
        if (TextUtils.isEmpty(keyWord)) {
            ToastUtils.showToast("关键字为空");
            return;
        }
//        String history_search = currShared.getString(SpKey.HISTORY_SEARCH, "");
//        dealSearchOld(history_search);
        showDialog();
        search(keyWord);
    }

    /**
     *
     */
    private void showDialog() {
        dialog = new AlertDialog.Builder(this).setMessage("正在搜索...").create();
        dialog.show();
    }

    /**
     * 开始搜索
     * lng经度
     * lat纬度
     * page:第几页
     * showNumber:显示个数
     * cityId:市ID
     * curCityId:当前地市ID
     * search:搜索条件
     *
     * @param keyWord
     */
    private void search(String keyWord) {
        BaseProtocal.builder(false).search(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("搜索结果", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    cancel();
                    HomeSearchResultBean homeSearchResultBean = new Gson().fromJson(response, HomeSearchResultBean.class);
                    List<HomeSearchResultBean.BusinessInfo> currBiList = homeSearchResultBean.biList;
                    setLoadData(currBiList);
                    adapter.notifyDataSetChanged();
                    dealVisibility();
                } else {
                    noData();
                }
            }

            @Override
            public void onFail(Exception e) {
                noData();
            }
        }, page, lon, lat, cityId, currCityId, keyWord);
    }

    private void dealSearchOld() {
        //        历史搜索纪录
        String hisSearchs = currShared.getString(SpKey.HISTORY_SEARCH, "");
//        hisSearch.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(hisSearchs)) {
//            hisSearch.setVisibility(View.VISIBLE);
            historyStrings = hisSearchs.split("#");
            adapter1.setDatas(historyStrings);
        }
    }

    private void dealSearchOld(String history_search) {
        if (TextUtils.isEmpty(history_search)) {
            sb.append(keyWord);
        } else {
            String[] strings = history_search.split("#");
            sb.delete(0, sb.length());
            if (strings.length > 3) {
                for (int i = strings.length - 1; i > strings.length - 4; i--) {
                    sb.append(strings[i] + "#");
                    if (i == strings.length - 3) {
                        sb.append(keyWord);
                    }
                }
            } else {
                for (int i = 0; i < strings.length; i++) {
                    sb.append(strings[i] + "#");
                    if (i == strings.length - 1)
                        sb.append(keyWord);
                }
            }
        }
        currShared.edit().putString(SpKey.HISTORY_SEARCH, sb.toString()).commit();
        historyStrings = sb.toString().split("#");
        adapter1.setDatas(historyStrings);
    }

    private void dealVisibility() {
        if (datas.size() > 0) {
            listInfo.setVisibility(View.VISIBLE);
            only_no.setVisibility(View.GONE);
            refresh.setVisibility(View.VISIBLE);
        } else {
            listInfo.setVisibility(View.GONE);
            only_no.setVisibility(View.VISIBLE);
            refresh.setVisibility(View.GONE);
        }
    }

    private void noData() {
        cancel();
        onRefreshError();
        if (datas.size() == 0) {
            listInfo.setVisibility(View.GONE);
            only_no.setVisibility(View.VISIBLE);
        }
    }

    public void cancel() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    //  加载数据
    @Override
    public void load(boolean isLoad) {
        if (TextUtils.isEmpty(keyWord)) {
            if (isLoad)
                refresh.setLoading(false);
            setRefreshDone();
            return;
        }

        if (isLoad)
            page++;
        search(keyWord);
    }

    class MyAdapter extends TypeAdapter {

        public MyAdapter(String[] strings) {
            super(strings);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//            条目较少，不做优化
            View view = UIUtils.inflate(R.layout.search_text);
            TextView textView = (TextView) view.findViewById(R.id.search_text);
            textView.setText(strings[position]);
            AutoUtils.autoSize(view);
            return view;
        }
    }
}
